import { Configdb } from "sapi-pro";
import { PKMaps } from "./maps";

export interface PKStorageConfig {
    mapIndex: number;
    runTime: number;
    buildTime: number;
    lives: number;
}

const defaultConfig: PKStorageConfig = {
    mapIndex: 0,
    runTime: 600,
    buildTime: 600,
    lives: 10,
};

/**跑酷配置管理 */
export class PKConfigManager {
    static readonly key = "parkourGame";

    static validate(config: Partial<PKStorageConfig>): PKStorageConfig {
        const validated: PKStorageConfig = { ...defaultConfig };

        if (
            typeof config.mapIndex === "number" &&
            config.mapIndex >= 0 &&
            config.mapIndex < Object.keys(PKMaps).length
        ) {
            validated.mapIndex = config.mapIndex;
        }

        if (typeof config.runTime === "number" && config.runTime > 0) {
            validated.runTime = config.runTime;
        }

        if (typeof config.buildTime === "number" && config.buildTime > 0) {
            validated.buildTime = config.buildTime;
        }

        if (typeof config.lives === "number" && config.lives > 0) {
            validated.lives = config.lives;
        }

        return validated;
    }

    static set(config: Partial<PKStorageConfig>) {
        const validConfig = this.validate(config);
        Configdb.setJSON(this.key, validConfig);
    }

    static get(): PKStorageConfig {
        const raw = Configdb.getJSON(this.key);
        return this.validate(raw ?? {});
    }
}
